package com.gupao.ldr.pattern.singleton.lazy;

import java.lang.reflect.Constructor;

/**
 * 懒汉式(静态内部类，线程安全)
 * 类加载特征：先加载内部类，然后加载外部类。
 */
public class LazyInnerClassSingleton {


    //使用反射可以暴力得到构造方法
    private LazyInnerClassSingleton(){

        if (LazyHolder.LAZY !=null){
            throw new RuntimeException("不允许创建多个实例");
        }

    }

    //LazyHolder里面的逻辑需要等到外部方法调用时才执行
    //巧妙使用内部类的特性
    //JVM底层执行逻辑，完美避免线程安全的问题
    public static LazyInnerClassSingleton getInstance(){
       return LazyHolder.LAZY;
    }


    private static class LazyHolder {
        private static final LazyInnerClassSingleton LAZY =new LazyInnerClassSingleton();

    }

    public static void main(String[] args) {
        try {
            Constructor<LazyInnerClassSingleton> constructor = LazyInnerClassSingleton.class.getDeclaredConstructor(null);
            //设置允许强制访问
            constructor.setAccessible(true);
            LazyInnerClassSingleton lazyInnerClassSingleton = constructor.newInstance();
            System.out.println(lazyInnerClassSingleton);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
